# -*- coding: utf-8 -*-
# @Time    : 2023/11/08 09:43
# @Author  : Jonny
# @File    : LuckDingtalkService.py
# @Describe: 钉钉逻辑服务层

import logging
import base64
import requests
import json

class LuckDingtalkService(object):

    def __init__(self, config):
        self.config = config

    CONTENT_TYPE = 'application/json'

    # 发送钉钉群机器人文本消息
    def send_text_msg_to_group(self, dingtalk_content, dingtalk_userid):
        try:
            agent_id = self.config["agent_id"]
            app_key = self.config["app_key"]
            app_secret = self.config["app_secret"]

            dingtalk_app_key = self.config["dingtalk_app_key"]
            dingtalk_app_secret = self.config["dingtalk_app_secret"]
            dingtalk_url = self.config["dingtalk_url"]
            dingtalk_url_basic_auth1 = self.config["dingtalk_url_basic_auth1"]
            dingtalk_url_basic_auth2 = self.config["dingtalk_url_basic_auth2"]
            dingtalk_robot_list = self.config["dingtalk_robot_list"]

            auth = str(base64.b64encode(f'{dingtalk_url_basic_auth1}:{dingtalk_url_basic_auth2}'.encode('utf-8')), 'utf-8')
            headers = {
                'Content-Type': self.CONTENT_TYPE,
                'Authorization': f'Basic {auth}'
            }
            url = f"{dingtalk_url}/sendTextMsgToGroup"

            if dingtalk_userid is None or dingtalk_userid == "":
                dingtalk_userid = "all"
            msg = {}
            if "all" == dingtalk_userid:
                msg = {
                    "agent_id": agent_id,
                    "app_key": app_key,
                    "app_secret": app_secret,

                    "dingtalk_app_key": dingtalk_app_key,
                    "dingtalk_app_secret": dingtalk_app_secret,
                    "dingtalk_robot_list": dingtalk_robot_list,
                    "dingtalk_content": dingtalk_content,
                    "dingtalk_at": {
                        "isAtAll": "true"
                    }
                }
            else:
                msg = {
                    "agent_id": agent_id,
                    "app_key": app_key,
                    "app_secret": app_secret,

                    "dingtalk_app_key": dingtalk_app_key,
                    "dingtalk_app_secret": dingtalk_app_secret,
                    "dingtalk_robot_list": dingtalk_robot_list,
                    "dingtalk_content": dingtalk_content,
                    "dingtalk_at": {
                        "isAtAll": "false",
                        "atUserIds": dingtalk_userid.split(',')
                    }
                }

            res = requests.post(url, data=json.dumps(msg), headers=headers)
            result = res.json()
            if res.status_code == 200:
                return result
            return {
                "code": 0,
                "msg": "发送钉钉群机器人文本消息 失败"
            }
        except Exception as e:
            raise e

    # 发送钉钉群机器人链接消息
    def send_link_msg_to_group(self, title, text, message_url):
        try:
            agent_id = self.config["agent_id"]
            app_key = self.config["app_key"]
            app_secret = self.config["app_secret"]

            dingtalk_app_key = self.config["dingtalk_app_key"]
            dingtalk_app_secret = self.config["dingtalk_app_secret"]
            dingtalk_url = self.config["dingtalk_url"]
            dingtalk_url_basic_auth1 = self.config["dingtalk_url_basic_auth1"]
            dingtalk_url_basic_auth2 = self.config["dingtalk_url_basic_auth2"]
            dingtalk_robot_list = self.config["dingtalk_robot_list"]

            msg = {
                "agent_id": agent_id,
                "app_key": app_key,
                "app_secret": app_secret,

                "dingtalk_app_key": dingtalk_app_key,
                "dingtalk_app_secret": dingtalk_app_secret,
                "dingtalk_robot_list": dingtalk_robot_list,
                "dingtalk_content": {
                    "text": text,
                    "title": title,
                    "picUrl": "http://www.ahyungui.com/Public/Upload/column/18/2021-01-06/7188548b-0984-4c6c-8fb3-ce0d8ff6a148.png",
                    "messageUrl": message_url
                }
            }

            auth = str(base64.b64encode(f'{dingtalk_url_basic_auth1}:{dingtalk_url_basic_auth2}'.encode('utf-8')),
                       'utf-8')
            headers = {
                'Content-Type': self.CONTENT_TYPE,
                'Authorization': f'Basic {auth}'
            }
            url = f"{dingtalk_url}/sendLinkMsgToGroup"
            res = requests.post(url, data=json.dumps(msg), headers=headers)
            result = res.json()
            if res.status_code == 200:
                return result
            return {
                "code": 0,
                "msg": "发送钉钉群机器人链接消息 失败"
            }
        except Exception as e:
            raise e

    # 发送钉钉群机器人FeedCard消息
    def send_feedcard_msg_to_group(self, mq_config, data):
        try:
            agent_id = self.config["agent_id"]
            app_key = self.config["app_key"]
            app_secret = self.config["app_secret"]

            dingtalk_app_key = self.config["dingtalk_app_key"]
            dingtalk_app_secret = self.config["dingtalk_app_secret"]
            dingtalk_url = self.config["dingtalk_url"]
            dingtalk_url_basic_auth1 = self.config["dingtalk_url_basic_auth1"]
            dingtalk_url_basic_auth2 = self.config["dingtalk_url_basic_auth2"]
            dingtalk_robot_list = self.config["dingtalk_robot_list"]

            mq_name = mq_config["mq_name"]
            mq_url = mq_config["mq_url"]
            if len(data) > 0:
                objects_list = []
                index = 0
                for row in data:
                    index = index + 1
                    s = f"{index}. {row['vhost']} {row['label']} {row['name']}"
                    d = {
                        "title": s,
                        "messageURL": f"{mq_url}"  # ,
                        # "picURL": "http://www.ahyungui.com/Public/headstatic/img/url_icon.png"
                    }
                    objects_list.append(d)

                s = f"{mq_name} {mq_url} MQ上有{len(data)}条异常消息数据"
                d = {
                    "title": s,
                    "messageURL": f"{mq_url}",
                    "picURL": "http://www.ahyungui.com/Public/Upload/column/18/2021-01-06/7188548b-0984-4c6c-8fb3-ce0d8ff6a148.png"
                }
                objects_list.insert(0, d)

                msg = {
                    "agent_id": agent_id,
                    "app_key": app_key,
                    "app_secret": app_secret,

                    "dingtalk_app_key": dingtalk_app_key,
                    "dingtalk_app_secret": dingtalk_app_secret,
                    "dingtalk_robot_list": dingtalk_robot_list,
                    "dingtalk_content_list": objects_list
                }
                auth = str(base64.b64encode(f'{dingtalk_url_basic_auth1}:{dingtalk_url_basic_auth2}'.encode('utf-8')),
                           'utf-8')
                headers = {
                    'Content-Type': self.CONTENT_TYPE,
                    'Authorization': f'Basic {auth}'
                }
                url = f"{dingtalk_url}/sendFeedcardMsgToGroup"
                res = requests.post(url, data=json.dumps(msg), headers=headers)
                result = res.json()
                if res.status_code == 200:
                    return result
                return {
                    "code": 0,
                    "msg": "发送钉钉群机器人FeedCard消息 失败"
                }
        except Exception as e:
            raise e

    # 发送钉钉群机器人Markdown消息
    def send_markdown_msg_to_group(self, dingtalk_content, dingtalk_userid):
        try:
            agent_id = self.config["agent_id"]
            app_key = self.config["app_key"]
            app_secret = self.config["app_secret"]

            dingtalk_app_key = self.config["dingtalk_app_key"]
            dingtalk_app_secret = self.config["dingtalk_app_secret"]
            dingtalk_url = self.config["dingtalk_url"]
            dingtalk_url_basic_auth1 = self.config["dingtalk_url_basic_auth1"]
            dingtalk_url_basic_auth2 = self.config["dingtalk_url_basic_auth2"]
            dingtalk_robot_list = self.config["dingtalk_robot_list"]

            auth = str(base64.b64encode(f'{dingtalk_url_basic_auth1}:{dingtalk_url_basic_auth2}'.encode('utf-8')), 'utf-8')
            headers = {
                'Content-Type': self.CONTENT_TYPE,
                'Authorization': f'Basic {auth}'
            }
            url = f"{dingtalk_url}/sendMarkdownMsgToGroup"

            if dingtalk_userid is None or dingtalk_userid == "":
                dingtalk_userid = "all"
            msg = {}
            if "all" == dingtalk_userid:
                msg = {
                    "agent_id": agent_id,
                    "app_key": app_key,
                    "app_secret": app_secret,

                    "dingtalk_app_key": dingtalk_app_key,
                    "dingtalk_app_secret": dingtalk_app_secret,
                    "dingtalk_robot_list": dingtalk_robot_list,
                    "dingtalk_content": dingtalk_content,
                    "dingtalk_at": {
                        "isAtAll": "true"
                    }
                }
            else:
                msg = {
                    "agent_id": agent_id,
                    "app_key": app_key,
                    "app_secret": app_secret,

                    "dingtalk_app_key": dingtalk_app_key,
                    "dingtalk_app_secret": dingtalk_app_secret,
                    "dingtalk_robot_list": dingtalk_robot_list,
                    "dingtalk_content": dingtalk_content,
                    "dingtalk_at": {
                        "isAtAll": "false",
                        "atUserIds": dingtalk_userid.split(',')
                    }
                }

            res = requests.post(url, data=json.dumps(msg), headers=headers)
            result = res.json()
            if res.status_code == 200:
                return result
            return {
                "code": 0,
                "msg": "发送钉钉群机器人Markdown消息 失败"
            }
        except Exception as e:
            raise e

    # 发送文本消息到个人信息
    def send_text_msg_to_user(self, dingtalk_content, dingtalk_userid):
        try:
            agent_id = self.config["agent_id"]
            app_key = self.config["app_key"]
            app_secret = self.config["app_secret"]

            dingtalk_app_key = self.config["dingtalk_app_key"]
            dingtalk_app_secret = self.config["dingtalk_app_secret"]
            dingtalk_url = self.config["dingtalk_url"]
            dingtalk_url_basic_auth1 = self.config["dingtalk_url_basic_auth1"]
            dingtalk_url_basic_auth2 = self.config["dingtalk_url_basic_auth2"]

            auth = str(base64.b64encode(f'{dingtalk_url_basic_auth1}:{dingtalk_url_basic_auth2}'.encode('utf-8')),
                       'utf-8')
            headers = {
                'Content-Type': self.CONTENT_TYPE,
                'Authorization': f'Basic {auth}'
            }
            url = f"{dingtalk_url}/sendTextMsgToPerson"

            if dingtalk_userid is not None and dingtalk_userid != "":
                msg = {
                    "agent_id": agent_id,
                    "app_key": app_key,
                    "app_secret": app_secret,

                    "dingtalk_app_key": dingtalk_app_key,
                    "dingtalk_app_secret": dingtalk_app_secret,
                    "dingtalk_content": dingtalk_content,
                    "dingtalk_userid_list": dingtalk_userid.split(',')
                }

            res = requests.post(url, data=json.dumps(msg), headers=headers)
            result = res.json()
            if res.status_code == 200:
                return result
            return {
                "code": 0,
                "msg": "发送钉钉群机器人Markdown消息 失败"
            }
        except Exception as e:
            raise e